mod auth;
mod config;
mod entities;
mod http_client;

use std::sync::Arc;

use crate::auth::{login_user, register_user, get_current_user, logout_user, get_current_jwt_token, check_login_status, get_current_user_from_session};
use crate::entities::{FishingCircleRequest, Location, LoginRequest, RegisterRequest, User, AuthResponse};
use crate::http_client::ApiClient;


#[tauri::command]
async fn save_fishing_circle(
    title: String,
    latitude: f64,
    longitude: f64,
    points: Vec<Location>,
    pics: Vec<String>,
    area: f64,
    description: Option<String>,
) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let request: FishingCircleRequest = FishingCircleRequest {
        title,
        latitude,
        longitude,
        points,
        pics,
        area,
        description,
    };

    let client = ApiClient::new();
    let response = client.save_fishing_circle(&request, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn login(credentials: LoginRequest) -> Result<AuthResponse, String> {
    login_user(credentials).await
}

#[tauri::command]
async fn register(user_info: RegisterRequest) -> Result<AuthResponse, String> {
    register_user(user_info).await
}

#[tauri::command]
async fn get_user_info(token: String) -> Result<Option<User>, String> {
    get_current_user(token)
}

#[tauri::command]
async fn logout(token: String) -> Result<bool, String> {
    logout_user(token)
}

#[tauri::command]
fn is_user_logged_in() -> Result<bool, String> {
    crate::auth::check_login_status()
}

#[tauri::command]
fn get_session_user() -> Result<Option<User>, String> {
    crate::auth::get_current_user_from_session()
}

#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
async fn upload_image(file_path: String, jwt_token: String) -> Result<String, String> {
    let client = ApiClient::new();
    
    match client.upload_file(&file_path, &jwt_token).await {
        Ok(upload_data) => Ok(upload_data.url),
        Err(error) => Err(format!("Upload failed: {}", error))
    }
}

#[tauri::command]
async fn upload_image_base64(file_name: String, base64_data: String, jwt_token: String) -> Result<String, String> {
    use base64::Engine;
    use crate::config::IMAGE_BASE_URL;
    
    // 解码base64数据
    let decoded_data = base64::engine::general_purpose::STANDARD
        .decode(&base64_data)
        .map_err(|e| format!("Failed to decode base64: {}", e))?;

    // 创建临时文件
    let temp_dir = std::env::temp_dir();
    let file_path = temp_dir.join(&file_name);
    
    // 写入临时文件
    tokio::fs::write(&file_path, decoded_data)
        .await
        .map_err(|e| format!("Failed to write temp file: {}", e))?;

    // 上传文件
    let client = ApiClient::new();
    let upload_data = client.upload_file(
        file_path.to_str().unwrap(),
        &jwt_token
    ).await?;

    // 清理临时文件
    let _ = tokio::fs::remove_file(&file_path).await;

    // 拼接完整的图片URL（使用图片服务器地址）
    let full_url = if upload_data.url.starts_with("http") {
        upload_data.url
    } else {
        let url_path = upload_data.url.trim_start_matches('/');
        format!("{}/{}", IMAGE_BASE_URL, url_path)
    };

    Ok(full_url)
}

// 获取协议列表
#[tauri::command]
async fn get_agreements(page_num: u32, page_size: u32, type_filter: String, enabled_filter: String) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_agreements(
        page_num,
        page_size,
        type_filter,
        enabled_filter,
        &jwt_token
    ).await?;
    
    Ok(response)
}

// 更新协议状态
#[tauri::command]
async fn update_agreement_status(id: String, enabled: String) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.update_agreement_status(
        id,
        enabled,
        &jwt_token
    ).await?;
    
    Ok(response)
}

// 获取等级设置列表
#[tauri::command]
async fn get_level_rules() -> Result<serde_json::Value, String> {
    println!("[DEBUG] get_level_rules command called");
    
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = match get_current_jwt_token() {
        Ok(token) => {
            println!("[DEBUG] JWT token retrieved successfully");
            token
        }
        Err(e) => {
            println!("[ERROR] Failed to get JWT token: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] Calling API client get_level_rules");
    let client = ApiClient::new();
    let response = match client.get_level_rules(&jwt_token).await {
        Ok(resp) => {
            println!("[DEBUG] API client returned success response");
            resp
        }
        Err(e) => {
            println!("[ERROR] API client returned error: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] get_level_rules command completed successfully");
    Ok(response)
}

// 获取钓点表单属性
#[tauri::command]
async fn get_spot_props() -> Result<serde_json::Value, String> {
    println!("[DEBUG] get_spot_props command called");
    
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = match get_current_jwt_token() {
        Ok(token) => {
            println!("[DEBUG] JWT token retrieved successfully");
            token
        }
        Err(e) => {
            println!("[ERROR] Failed to get JWT token: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] Calling API client get_spot_props");
    let client = ApiClient::new();
    let response = match client.get_spot_props(&jwt_token).await {
        Ok(resp) => {
            println!("[DEBUG] API client returned success response");
            resp
        }
        Err(e) => {
            println!("[ERROR] API client returned error: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] get_spot_props command completed successfully");
    Ok(response)
}

// 添加等级规则
#[tauri::command]
async fn add_level_rule(
    level_name: String,
    min_points: String,
    max_points: String,
    core_trait: String,
    uri: String,
    upgrade_threshold: String
) -> Result<serde_json::Value, String> {
    println!("[DEBUG] add_level_rule command called");
    
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = match get_current_jwt_token() {
        Ok(token) => {
            println!("[DEBUG] JWT token retrieved for add_level_rule");
            token
        }
        Err(e) => {
            println!("[ERROR] Failed to get JWT token for add_level_rule: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] Calling API client add_level_rule");
    let client = ApiClient::new();
    let response = match client.add_level_rule(
        level_name,
        min_points,
        max_points,
        core_trait,
        uri,
        upgrade_threshold,
        &jwt_token
    ).await {
        Ok(resp) => {
            println!("[DEBUG] API client add_level_rule returned success");
            resp
        }
        Err(e) => {
            println!("[ERROR] API client add_level_rule returned error: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] add_level_rule command completed successfully");
    Ok(response)
}

// 更新等级规则
#[tauri::command]
async fn update_level_rule(
    level_id: String,
    level_name: String,
    min_points: String,
    max_points: String,
    core_trait: String,
    uri: String,
    upgrade_threshold: String
) -> Result<serde_json::Value, String> {
    println!("[DEBUG] update_level_rule command called");
    
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = match get_current_jwt_token() {
        Ok(token) => {
            println!("[DEBUG] JWT token retrieved for update_level_rule");
            token
        }
        Err(e) => {
            println!("[ERROR] Failed to get JWT token for update_level_rule: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] Calling API client update_level_rule");
    let client = ApiClient::new();
    let response = match client.update_level_rule(
        level_id,
        level_name,
        min_points,
        max_points,
        core_trait,
        uri,
        upgrade_threshold,
        &jwt_token
    ).await {
        Ok(resp) => {
            println!("[DEBUG] API client update_level_rule returned success");
            resp
        }
        Err(e) => {
            println!("[ERROR] API client update_level_rule returned error: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] update_level_rule command completed successfully");
    Ok(response)
}

// 获取积分设置列表
#[tauri::command]
async fn get_credit_rules() -> Result<serde_json::Value, String> {
    println!("[DEBUG] get_credit_rules command called");
    
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = match get_current_jwt_token() {
        Ok(token) => {
            println!("[DEBUG] JWT token retrieved successfully");
            token
        }
        Err(e) => {
            println!("[ERROR] Failed to get JWT token: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] Calling API client get_credit_rules");
    let client = ApiClient::new();
    let response = match client.get_credit_rules(&jwt_token).await {
        Ok(resp) => {
            println!("[DEBUG] API client returned success response");
            resp
        }
        Err(e) => {
            println!("[ERROR] API client returned error: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] get_credit_rules command completed successfully");
    Ok(response)
}

// 添加积分规则
#[tauri::command]
async fn add_credit_rule(
    level_range_start: String,
    level_range_end: String,
    behavior_desc: String,
    points: String,
    limit_desc: String,
    sort_order: String
) -> Result<serde_json::Value, String> {
    println!("[DEBUG] add_credit_rule command called");
    
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = match get_current_jwt_token() {
        Ok(token) => {
            println!("[DEBUG] JWT token retrieved for add_credit_rule");
            token
        }
        Err(e) => {
            println!("[ERROR] Failed to get JWT token for add_credit_rule: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] Calling API client add_credit_rule");
    let client = ApiClient::new();
    let response = match client.add_credit_rule(
        level_range_start,
        level_range_end,
        behavior_desc,
        points,
        limit_desc,
        sort_order,
        &jwt_token
    ).await {
        Ok(resp) => {
            println!("[DEBUG] API client add_credit_rule returned success");
            resp
        }
        Err(e) => {
            println!("[ERROR] API client add_credit_rule returned error: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] add_credit_rule command completed successfully");
    Ok(response)
}

// 更新积分规则
#[tauri::command]
async fn update_credit_rule(
    credit_id: String,
    level_range_start: String,
    level_range_end: String,
    behavior_desc: String,
    points: String,
    limit_desc: String,
    sort_order: String
) -> Result<serde_json::Value, String> {
    println!("[DEBUG] update_credit_rule command called");
    
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = match get_current_jwt_token() {
        Ok(token) => {
            println!("[DEBUG] JWT token retrieved for update_credit_rule");
            token
        }
        Err(e) => {
            println!("[ERROR] Failed to get JWT token for update_credit_rule: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] Calling API client update_credit_rule");
    let client = ApiClient::new();
    let response = match client.update_credit_rule(
        credit_id,
        level_range_start,
        level_range_end,
        behavior_desc,
        points,
        limit_desc,
        sort_order,
        &jwt_token
    ).await {
        Ok(resp) => {
            println!("[DEBUG] API client update_credit_rule returned success");
            resp
        }
        Err(e) => {
            println!("[ERROR] API client update_credit_rule returned error: {}", e);
            return Err(e);
        }
    };
    
    println!("[DEBUG] update_credit_rule command completed successfully");
    Ok(response)
}

// 获取新版本协议内容
#[tauri::command]
async fn get_new_version_content(id: String) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_new_version_content(
        id,
        &jwt_token
    ).await?;
    
    Ok(response)
}

// 更新协议或创建新版本
#[tauri::command]
async fn update_agreement(id: String, content: String) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    let client = ApiClient::new();
    let response = client.update_agreement(
        id,
        content,
        &jwt_token
    ).await?;
    
    Ok(response)
}

// 新增协议
#[tauri::command]
async fn add_new_agreement(r#type: String, content: String) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    let client = ApiClient::new();
    let response = client.add_new_agreement(
        r#type,
        content,
        &jwt_token
    ).await?;
    
    Ok(response)
}

#[tauri::command]
async fn upload_image_file(file_path: String, jwt_token: String) -> Result<String, String> {
    use crate::config::IMAGE_BASE_URL;
    
    let client = ApiClient::new();
    let upload_data = client.upload_file(&file_path, &jwt_token).await?;

    // 拼接完整的图片URL（使用图片服务器地址）
    let full_url = if upload_data.url.starts_with("http") {
        upload_data.url
    } else {
        let url_path = upload_data.url.trim_start_matches('/');
        format!("{}/{}", IMAGE_BASE_URL, url_path)
    };

    Ok(full_url)
}

#[tauri::command]
async fn get_fishing_circles(page: u32, size: u32) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_fishing_circles(page, size, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_fishing_circle_detail(id: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_fishing_circle_detail(id.clone(), &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn mark_circle_active(id: String, is_active: i32) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.mark_circle_active(id.clone(), is_active, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn delete_fishing_circle(id: String) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.delete_fishing_circle(id.clone(), &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn update_fishing_circle(
    id: String,
    title: String,
    description: String,
    pics: Vec<String>
) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.update_fishing_circle(
        id.clone(), 
        title, 
        description, 
        pics, 
        &jwt_token
    ).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_circle_match(
    id: String
) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_circle_match(id.clone(), &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn save_circle_match(
    id: String,
    spot_ids: Vec<String>
) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.save_circle_match(id, spot_ids, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_circle_spots(
    id: String,
    page: u32,
    size: u32
) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_circle_spots(id, page, size, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_circle_messages(
    city_code: String,
    cursor: Option<String>,
    size: u32
) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_circle_messages(city_code, cursor, size, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_circle_cities() -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_circle_cities( &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn search_cities(page_num: u32, page_size: u32, city: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.search_cities(page_num, page_size, &city, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn add_city(city_code: String, city: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.add_circle_city(&city_code, &city, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn add_spot(spot: serde_json::Value) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.add_spot(&spot, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn refresh_cities() -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.refresh_cities(&jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn search_circle_cities(keyword: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.search_circle_cities(keyword, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_users(page: u32, size: u32) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_users(page, size, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn create_user(username: String, email: String, phone_no: String, password: String) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    
    let mut user_data = std::collections::HashMap::new();
    user_data.insert("username", username.as_str());
    user_data.insert("email", email.as_str());
    user_data.insert("phoneNo", phone_no.as_str());
    user_data.insert("password", password.as_str());
    
    let response = client.create_user(&user_data, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn delete_user(user_id: u64) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.delete_user(user_id, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn enable_user(user_id: String, status: i32) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.enable_user(user_id, status, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn switch_admin_role(user_id: String, is_admin: i32) -> Result<String, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.switch_admin_role(user_id, is_admin, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn search_users(username: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.search_users(username, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_spots(query: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_spots(&query, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_fishing_spot_by_id(id: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_fishing_spot_by_id(id, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn toggle_spot_disabled(spot_id: String, disabled: bool) -> Result<bool, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.toggle_spot_disabled(spot_id, disabled, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_collected_spots(page_num: u32, page_size: u32, is_collected: u32, spot_id: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_collected_spots(page_num, page_size, is_collected, spot_id, &jwt_token).await?;
    
    Ok(response)
}

#[tauri::command]
async fn get_spot_harvests(page_num: u32, page_size: u32, spot_id: String) -> Result<serde_json::Value, String> {
    // 从会话管理获取当前用户的 JWT token
    let jwt_token = get_current_jwt_token()?;
    
    let client = ApiClient::new();
    let response = client.get_spot_harvests(page_num, page_size, spot_id, &jwt_token).await?;
    
    Ok(response)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_fs::init())
        .invoke_handler(tauri::generate_handler![
            greet,
            login,
            register,
            get_user_info,
            logout,
            is_user_logged_in,
            get_session_user,
            upload_image,
            upload_image_base64,
            upload_image_file,
            save_fishing_circle,
            get_fishing_circles,
            get_fishing_circle_detail,
            mark_circle_active,
            delete_fishing_circle,
            update_fishing_circle,
            get_circle_match,
            save_circle_match,
            get_circle_spots,
            get_circle_messages,
            get_circle_cities,
            search_cities,
            search_circle_cities,
            refresh_cities,
            add_city,
            get_users,
            create_user,
            delete_user,
            enable_user,
            switch_admin_role,
            search_users,
            get_spots,
            get_fishing_spot_by_id,
            toggle_spot_disabled,
            get_collected_spots,
            get_spot_harvests,
            add_spot,
            get_agreements,
            get_level_rules,
            get_spot_props,
            add_level_rule,
            update_level_rule,
            get_credit_rules,
            add_credit_rule,
            update_credit_rule,
            update_agreement_status,
            get_new_version_content,
            update_agreement,
            add_new_agreement
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
